package com.ruoyi.different.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.WxAppConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.RedisUtils;

import com.ruoyi.common.utils.wxSend.common.Constant;
import com.ruoyi.common.utils.wxSend.common.HttpClientUtil;
import com.ruoyi.common.utils.wxSend.weixinmoban.TemplateMessage;
import com.ruoyi.system.service.ISysUserService;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WeixinGetOpenId {

    private static final  org.slf4j.Logger logger = LoggerFactory.getLogger(WeixinGetOpenId.class);
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxAppConfig wxAppConfig;


    @Autowired
    private ISysUserService userService;


    public String sendWarningByWechat(String openId, TreeMap<String, String> miniprograms, List<String> keys,List<String> values, String temlateid) {
        //获取redis中存的access_token
        String access_token = String.valueOf(redisUtils.get("access_token"));
        StringBuffer resBuff = new StringBuffer();
        try {
            String templateMsgUrl = Constant.templateMsgUrl;
            System.out.println(Constant.getAccess_token_url());
           // String resultInfo = HttpClientUtil.doGet(Constant.getAccess_token_url());

            templateMsgUrl = templateMsgUrl.replace("ACCESS_TOKEN", access_token);
           // templateMsgUrl = templateMsgUrl.replace("ACCESS_TOKEN", resultInfo);
            //封装请求体
           // Template template = new Template();
            TemplateMessage template = new TemplateMessage();
            template.setTemplate_id(temlateid);
            // 设置点击跳转的路径
            template.setUrl("http://mp.weixin.qq.com");
            // 主要是这里， 设置小程序的appid和转发的页面
            /*TreeMap<String, String> miniprograms = new TreeMap<String, String>();
            miniprograms.put("appid","wx19b86a5fba0825ce");
            miniprograms.put("pagepath","pages/index/index?temp=1");// 注意，这里是支持传参的！！！*/
            template.setMiniprogram(miniprograms);
            //List<TpParam> templateParams = new ArrayList<>();
            // 设置消息内容和对应的颜色
            TreeMap<String, TreeMap<String, String>> params = new TreeMap<String, TreeMap<String, String>>();
           // TpParam first = new TpParam("first", content + "\\r\\n", "#DB1A1B");
            //TpParam keyword1 = new TpParam("thing1", "test" + "\\r\\n", "#DB1A1B");
            //TpParam keyword2 = new TpParam("thing7",  "test1", "#DB1A1B");
            //TpParam keyword3 = new TpParam("phone_number5", "1234567891", "#DB1A1B");
            //TpParam remark = new TpParam("time4", "2023-12-25", "#DB1A1B");
            /*params.put("thing1", TemplateMessage.item("test", "#DB1A1B"));
            params.put("thing7", TemplateMessage.item("test1", "#DB1A1B"));
            params.put("phone_number5", TemplateMessage.item("1234567891", "#DB1A1B"));
            params.put("time4", TemplateMessage.item(sendDateTime, "#DB1A1B"));*/
            for (int i = 0; i < keys.size(); i++) {
                params.put(keys.get(i), TemplateMessage.item(values.get(i), "#DB1A1B"));
            }
            template.setData(params);
           // templateParams.add(first);
            //templateParams.add(keyword1);
            //templateParams.add(keyword2);
            //templateParams.add(keyword3);
            //templateParams.add(remark);
            //template.setTpParamList(templateParams);

            template.setTouser(openId);
            //JSONObject data = JSONObject.fromObject(temp);
            String paramStr = JSONUtil.toJsonStr(template);

           // String paramStr = template.toJSON();
            //System.out.println(paramStr);
            //System.out.println(templateMsgUrl);
            String resJson = HttpClientUtil.doTemplateMsgPost(templateMsgUrl, paramStr);
            System.out.println(resJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "发送成功";
    }

    //获取小程序openid
    public Map<String,String> getXcxOpenId(String code, String encryptedIv, String encryptedData){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppConfig.getAppId() + "&secret=" + wxAppConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        if(restTemplate==null){
            restTemplate = new RestTemplate();
        }
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);

        //获取session_key和openid
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        String unionid = jsonObject.getString("unionid");

        //解密
        String decryptResult = "";
        try {
            //如果没有绑定微信开放平台，解析结果是没有unionid的。
            decryptResult = decrypt(sessionKey,encryptedIv,encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject jsonObject1 = JSONObject.parseObject(decryptResult);
       // String unionid = jsonObject1.getString("unionid");
       // String openId = jsonObject.getString("openId");
        //获取nickName
        String nickName = jsonObject.getString("nickName");
        //获取头像
        String avatarUrl = jsonObject.getString("avatarUrl");
        HashMap<String, String> map = new HashMap<>();
        map.put("openId", openid);
        map.put("unionid", unionid);
        map.put("nickName", nickName);
        map.put("avatarUrl", avatarUrl);
        return map;


    }

    private String decrypt(String sessionKey,String encryptedIv,String encryptedData) throws Exception {
        //转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 如果密钥不足16位，那么就补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }

        // 如果初始向量不足16位，也补足
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            logger.info("解析错误！");
            e.printStackTrace();
        }

        //解析解密后的字符串
        return resultStr;
    }


    //获取公众号openid  存公众号openid
    public  void  getGzhOpenid() {
        String access_token = String.valueOf(redisUtils.get("access_token"));
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
        if(restTemplate==null){
            restTemplate = new RestTemplate();
        }
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);

        //获取公众号用户列表
        String data = jsonObject.getString("data");
        JSONObject dataJson = JSONObject.parseObject(data);
        String openid = dataJson.getString("openid");
        JSONArray objects = JSONUtil.parseArray(openid);
        List<String> strings = JSONUtil.toList(objects, String.class);

        //获取用户列表
        //List<SysUser> sysUsers = userService.selectUserListOpen(new SysUser());
        List<SysUser> sysUsers = userService.list();
        List<String> collect = sysUsers.stream().filter(x->Objects.nonNull(x.getUnionId())).map(SysUser::getUnionId).collect(Collectors.toList());

        //两个集合求交集
        List<String> resultList = new ArrayList<>();
        strings.stream().forEach(a1->{
            if (collect.contains(a1)){
                resultList.add(a1);
            }
        });
        //两个集合求差
        Collection<String> disjunction = CollectionUtil.disjunction(strings, resultList);
        List<String> collect1 = disjunction.stream().collect(Collectors.toList());

        //获取用户的unionid
        if (Objects.nonNull(collect1)&&collect1.size()>0){
            ArrayList<Map<String, String>> maps = new ArrayList<>();
            for (String id : collect1) {
                String url1 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+id+"&lang=zh_CN";
                if(restTemplate==null){
                    restTemplate = new RestTemplate();
                }
                String res1 = restTemplate.getForObject(url1, String.class);
                JSONObject jsonObject1 = JSONObject.parseObject(res1);
                //获取unionid
                String unionid = jsonObject1.getString("unionid");
                //HashMap<String, String> map = new HashMap<>();
                //map.put("unionid", unionid);
                //map.put("openid", id);
                //maps.add(map);


                //去数据库查询对应的unionid
               /* QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SysUser::getUnionId, unionid);*/
               /* SysUser sysUser = new SysUser();
                sysUser.setUnionId(unionid);*/

                if (Objects.nonNull(unionid)){
                    QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysUser::getUnionId, unionid);
                    List<SysUser> list = userService.list(queryWrapper);
                    if (Objects.nonNull(list) && list.size()>0){
                        SysUser user = list.get(0);
                        user.setGzhopenId(id);
                        // userService.updateUser(user);
                        QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda().eq(SysUser::getUserId, user.getUserId());
                        userService.update(user, queryWrapper1);
                    }

                }
               /* List<SysUser> sysUsers1 = userService.selectUserListOpen(sysUser);
                // List<SysUser> sysUsers1 = userService.list(queryWrapper);
                if (sysUsers1.size()>0){
                    sysUsers1.get(0).setGzhopenId(id);
                    userService.updateUser(sysUsers1.get(0));
                }*/
            }
        }

    }



    public  String  getGzhOpenidByCode(String code) {
        //String access_token = String.valueOf(redisUtils.get("access_token"));
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constant.APPID+"&secret="+Constant.APPSECRET+"&code="+code+"&grant_type=authorization_code";
        if(restTemplate==null){
            restTemplate = new RestTemplate();
        }
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String openid1 = jsonObject.getString("openid");

        return openid1;

    }
}
